﻿// Base type for all the fields that have a field type and a tool button
define([
    'Wjs/ui/widgets/fields/FieldBase',
    'Wjs/ui/widgets/fields/TextField',
    'Wjs/ui/widgets/foundation/ViewHashContainer'
],
function () {
    'use strict';

    return Wjs.defineOnce({

        type: 'ToolField',

        internal: {

            base: Wjs.getType('FieldBase'),

            mixins: [
                Wjs.getType('HashContainer')
            ],

            initialize: function () {

                this.addClass('wjs-tool-field');

                // Create a text field since it is the most used
                this.setField(

                    Wjs.new('TextField')
                );
            }

        },

        setName: function (name) {

            this.getField().setName(name);

            return this;
        },

        setValue: function (value) {

            this.getField().setValue(value);

            return this;
        },

        getValue: function () {

            return this.getField().getValue();
        },

        setField: function (field) {
            var me = this;

            field.addClass('wjs-display-flex-1');

            field.onBlur(function (evt) { // Route this event from the child to the parent
                var form = me.getForm();

                // Some validation can be triggered on the blur event
                me.validate(form.validationContext, true /* validateOnBlur */);

                if (me.blurHandler) {

                    me.blurHandler(evt);
                }
            });

            if (this.getSection('field')) {

                this.replaceSection('field', field);
            }
            else {

                this.addSection('field', field);
            }

            return this;
        },

        getField: function () {

            return this.getSection('field');
        },

        setTool: function (tool) {

            if (this.getSection('tool')) {

                this.replaceSection('tool', tool);
            }
            else {

                this.addSection('tool', tool);
            }

            return this;
        },

        isModified: function () {

            return this.getField().isModified();
        },

        enable: function () {

            this.getField().enable();

            return this;
        },

        disable: function () {

            this.field.disable();

            return this;
        }

    });

});